package com.aiyan.edu.framework.utils;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by mrt on 2018/5/25.
 */
public class Oauth2Util {

    public static UserJwt getUserJwtFromHeader(HttpServletRequest request) {
        Map<String, String> jwtClaims = Oauth2Util.getJwtClaimsFromHeader(request);
        if (jwtClaims == null || jwtClaims.get("id").equals("")) {
            return null;
        }
        UserJwt userJwt = new UserJwt();
        userJwt.setId(jwtClaims.get("id"));
        userJwt.setName(jwtClaims.get("name"));
        userJwt.setCompanyId(jwtClaims.get("companyId"));
        userJwt.setUtype(jwtClaims.get("utype"));
        userJwt.setUserpic(jwtClaims.get("userpic"));
        return userJwt;
    }

    public static UserJwt decodeUserJwt(String jwt) {
        Map<String, String> map = null;
        try {
            //解析jwt
            //得到 jwt中的用户信息
            String claims = JwtHelper.decode(jwt).getClaims();
            //将jwt转为Map
            map = JSON.parseObject(claims, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        UserJwt userJwt = new UserJwt();
        userJwt.setId(map.get("id"));
        userJwt.setName(map.get("name"));
        userJwt.setCompanyId(map.get("companyId"));
        userJwt.setUtype(map.get("utype"));
        userJwt.setUserpic(map.get("userpic"));
        return userJwt;
    }

    @Data
    public static class UserJwt {
        private String id;
        private String name;
        private String userpic;
        private String utype;
        private String companyId;
    }

    public static Map<String, String> getJwtClaimsFromHeader(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        //取出头信息
        String authorization = request.getHeader("Authorization");
        if (authorization == null || authorization.equals("") || authorization.indexOf("Bearer") < 0) {
            return null;
        }
        //从Bearer 后边开始取出token
        String token = authorization.substring(7);
        Map<String, String> map = null;
        try {
            //解析jwt
            Jwt decode = JwtHelper.decode(token);
            //得到 jwt中的用户信息
            String claims = decode.getClaims();
            //将jwt转为Map
            map = JSON.parseObject(claims, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
